import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/util/data_type.dart';
import 'package:freedom/util/http.dart';
import 'package:freedom/util/page_info.dart';

typedef BuildItem = Widget Function(dynamic data);

typedef LoadingData = Widget Function(PageInfo data);

const String _dataItemNodeConst = "records";
const String _pageSizeNodeConst = "size";
const String _pageCurrentNodeConst = "current";
const String _pageTotalNodeConst = "total";
const String _pagesNodeConst = "pages";

class PagingEasyRefresh extends StatefulWidget {
  final BuildItem? buildItem;
  final PageInfo? pageInfo;
  final String? dataItemNode;
  final String? pageSizeNode;
  final String? pageCurrentNode;
  final String? pageTotalNode;
  final String? pagesNode;
  final String? url;
  final Map<String, dynamic>? parame;

  const PagingEasyRefresh(
      {super.key,
      this.buildItem,
      this.pageInfo,
      this.dataItemNode = _dataItemNodeConst,
      this.pageSizeNode = _pageSizeNodeConst,
      this.pageCurrentNode = _pageCurrentNodeConst,
      this.pageTotalNode = _pageTotalNodeConst,
      this.pagesNode = _pagesNodeConst,
      this.url,
      this.parame});

  @override
  PagingEasyRefreshState createState() => PagingEasyRefreshState();
}

class PagingEasyRefreshState extends State<PagingEasyRefresh> {
  EasyRefreshController? _controller;
  PageInfo? _pageInfo;
  String? _dataItemNode;
  String? _pageSizeNode;
  String? _pageCurrentNode;
  String? _pagesNode;
  List<dynamic>? pageData;
  BuildItem? _buildItem;
  Map<String, dynamic>? _parame;

  bool fistLoading = true;

  @override
  void initState() {
    super.initState();
    _parame = widget.parame ?? {};
    _buildItem = widget.buildItem;
    _dataItemNode = widget.dataItemNode;
    _pageSizeNode = widget.pageSizeNode;
    _pageCurrentNode = widget.pageCurrentNode;
    _pagesNode = widget.pagesNode;
    pageData = [];
    _pageInfo = widget.pageInfo ?? PageInfo.init(1, 5);
    initData();
    _controller = EasyRefreshController();
  }

  void initData({LoadingData? success, bool reflush = false}) {
    if (widget.url == null) {
      return;
    }
    initParamePageInfo();
    Http.getInstance().request<Restful>(
        contentType: ContentType.json,
        widget.url,
        data: _parame, success: (data) {
      if (reflush) {
        pageData = [];
        _controller!.resetLoadState();
      }
      if (fistLoading) {
        fistLoading = false;
      }
      Map<dynamic, dynamic> resultData;
      if (data.body is! Map) {
        setState(() {});
        return;
      }
      resultData = asT<Map<dynamic, dynamic>>(data.body)!;
      if (resultData[_dataItemNode] is! List) {
        return;
      }
      List<dynamic> items = List.castFrom(resultData[_dataItemNode]);
      for (var element in items) {
        try {
          var item = _buildItem!(element);
          pageData!.add(item);
        } catch (e) {}
      }
      if (null != success) {
        success(PageInfo.factory(
            current: resultData[_pageCurrentNode],
            pages: resultData[_pagesNode]));
      }
      _controller!.finishLoad(
          noMore: resultData[_pagesNode] == resultData[_pageCurrentNode]);

      setState(() {});
    }, error: (data) {
      if (fistLoading) {
        fistLoading = false;
      }
    });
  }

  void initParamePageInfo() {
    _parame![_pageCurrentNode!] = _pageInfo!.current;
    _parame![_pageSizeNode!] = _pageInfo!.size;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        pageData!.isEmpty
            ? AnimatedContainer(
                duration: const Duration(microseconds: 200),
                child: Center(
                    child: fistLoading
                        ? const CircularProgressIndicator()
                        : Text(
                            "暂时没有相关数据",
                            style: TextStyle(fontSize: 16.sp),
                          )),
              )
            : const SizedBox(),
        EasyRefresh.custom(
          enableControlFinishRefresh: false,
          enableControlFinishLoad: true,
          controller: _controller,
          header: ClassicalHeader(
              refreshText: "下拉刷新",
              refreshingText: "刷新数据中...",
              refreshReadyText: "释放手刷新",
              refreshedText: "刷新完成"),
          footer: ClassicalFooter(
              loadText: "加载更多",
              loadingText: "正在加载...",
              loadedText: "加载完成",
              noMoreText: "没有更多数据了..."),
          onRefresh: () async {
            _pageInfo!.current = 1;
            initData(reflush: true);
          },
          onLoad: () async {
            _pageInfo!.current = _pageInfo!.current! + 1;
            initData();
          },
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return pageData![index];
                },
                childCount: pageData!.length,
              ),
            ),
          ],
        )
      ],
    );
  }
}
